package com.cuijq.dubbo.core.server;

import com.alibaba.nacos.api.exception.NacosException;
import com.cuijq.dubbo.demo.HelloService;
import com.cuijq.dubbo.demo.Invocation;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class NettyClient implements ApplicationRunner {

    @Autowired
    Bootstrap bootstrap;

    @Value("${netty.port:8080}")
    Integer port;

    @Autowired
    NioEventLoopGroup clientWorker;

    NettyClientHandler clientHandler;

    @Autowired
    private DiscoveryClient discoveryClient;


    private Channel channel;
    private static ExecutorService executorService = Executors.newCachedThreadPool();

    public void start(int port, String hostName) {
        clientHandler = new NettyClientHandler();
        bootstrap.group(clientWorker)
                .channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(
                        this.getClass().getClassLoader())));
                ch.pipeline().addLast("encoder", new ObjectEncoder());
                ch.pipeline().addLast(clientHandler);
            }
        });
        try {
            ChannelFuture f = bootstrap.connect(hostName, port).sync();
            channel = f.channel();
            channel.closeFuture().addListener((ChannelFutureListener) future -> {
                clientWorker.shutdownGracefully();
            });

        } catch (InterruptedException e) {
            e.printStackTrace();
            stop();
        }
    }

    public String send(String host, int port, Invocation invocation) {
        if (clientHandler == null) {
            start(port, host);
        }
        clientHandler.setInvocation(invocation);
        try {
            return (String) executorService.submit(clientHandler).get();
        } catch (Exception e) {
            e.printStackTrace();
            return "nettyClient";
        }
    }

    @Override
    public void run(ApplicationArguments args) throws NacosException {
        List<ServiceInstance> instances = discoveryClient.getInstances("netty-server");
        if (instances != null) {
            ServiceInstance instance = instances.get(new Random().nextInt(instances.size()));
            HelloService helloService = ProxyFactory.getProxy(this, HelloService.class, instance);
            String result = helloService.sayHello("崔晋强");
            log.info("返回数据{}", result);
        } else {
            log.info("未注册到注册中心");
        }
    }

    @PreDestroy
    public void stop() {
        if (channel != null) {
            channel.close();
        }
    }

    public boolean isRunning() {
        if (channel.isActive()) {
            return true;
        } else {
            return false;
        }
    }
}
